package com.warm.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.warm.core.domain.AjaxResult;
import com.warm.core.page.BaseController;
import com.warm.core.page.TableDataInfo;
import com.warm.excel.poi.utils.ExcelUtil;
import com.warm.log.annotation.Log;
import com.warm.log.enums.BusinessType;
import com.warm.pom.satoken.utils.LoginUtils;
import com.warm.system.api.LoginUser;
import com.warm.select.api.orm.domain.sys.SysDept;
import com.warm.select.api.orm.domain.sys.SysRole;
import com.warm.select.api.orm.domain.sys.SysUser;
import com.warm.select.api.orm.domain.sys.SysUserRole;
import com.warm.system.service.*;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;

import java.util.List;

/**
 * 角色信息
 *
 * @author warm
 */
@Valid
@Controller
@Mapping("/system/role")
public class SysRoleController extends BaseController {
    @Inject
    private ISysRoleService roleService;

    @Inject
    private TokenService tokenService;

    @Inject
    private SysPermissionService permissionService;

    @Inject
    private ISysUserService userService;

    @Inject
    private ISysDeptService deptService;

    @SaCheckPermission("system:role:list")
    @Get
    @Mapping("/list")
    public TableDataInfo<SysRole> list(SysRole role) {
        return roleService.selectRolePage(role);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:role:export")
    @Post
    @Mapping("/export")
    public void export(Context ctx, SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(ctx, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @SaCheckPermission("system:role:query")
    @Get
    @Mapping(value = "/{roleId}")
    public AjaxResult getInfo(Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @SaCheckPermission("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @Post
    @Mapping
    public AjaxResult add(@Validated SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(LoginUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @Put
    @Mapping
    public AjaxResult edit(@Validated SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role)) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(LoginUtils.getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = LoginUtils.getLoginUser();
            if (ObjectUtil.isNotNull(loginUser.getUser()) && !LoginUtils.isAdminU(loginUser.getUser().getUserId())) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @Put
    @Mapping("/dataScope")
    public AjaxResult dataScope(SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @Put
    @Mapping("/changeStatus")
    public AjaxResult changeStatus(SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(LoginUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @SaCheckPermission("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @Delete
    @Mapping("/{roleIds}")
    public AjaxResult remove(Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @SaCheckPermission("system:role:query")
    @Get
    @Mapping("/optionselect")
    public AjaxResult optionselect() {
        return success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @SaCheckPermission("system:role:list")
    @Get
    @Mapping("/authUser/allocatedList")
    public TableDataInfo<SysUser> allocatedList(SysUser user) {
        return userService.selectAllocatedPage(user);
    }

    /**
     * 查询未分配用户角色列表
     */
    @SaCheckPermission("system:role:list")
    @Get
    @Mapping("/authUser/unallocatedList")
    public TableDataInfo<SysUser> unallocatedList(SysUser user) {
        return userService.selectUnallocatedPage(user);
    }

    /**
     * 取消授权用户
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @Put
    @Mapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(SysUserRole userRole) {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @Put
    @Mapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @Put
    @Mapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @SaCheckPermission("system:role:query")
    @Get
    @Mapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(Long roleId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
